#!/bin/groovy
/*
 * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The OpenAirInterface Software Alliance licenses this file to You under
 * the terms found in the LICENSE file in the root of this source tree.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *-------------------------------------------------------------------------------
 * For more information about the OpenAirInterface (OAI) Software Alliance:
 *      contact@openairinterface.org
 */

//-------------------------------------------------------------------------------
// Abstraction function to send social media messages:
// like on Slack or Mattermost
def sendSocialMediaMessage(pipeChannel, pipeColor, pipeMessage) {
  if (params.pipelineUsesSlack != null) {
    if (params.pipelineUsesSlack) {
      slackSend channel: pipeChannel, color: pipeColor, message: pipeMessage
    }
  }
}

// Location of the CN executor node
def cn_ci_host = params.Host_CN_CI_Server

// for lock
def cn_ci_resource = params.DockerContainers

// Location of the 2nd CN executor
def new_host_flag = false
def new_host = ""
def new_host_user = ""

// Variables to pass to the FED Test job
def mme_tag = 'develop'
def mme_branch = 'develop'

//-------------------------------------------------------------------------------
// Pipeline start
pipeline {
  agent {
    label cn_ci_host
  }
  options {
    disableConcurrentBuilds()
    timestamps()
    ansiColor('xterm')
    lock(cn_ci_resource)
  }

  stages {
    stage ('Verify Parameters') {
      steps {
        script {
          echo '\u2705 \u001B[32mVerify Parameters\u001B[0m'

          JOB_TIMESTAMP = sh returnStdout: true, script: 'date --utc --rfc-3339=seconds | sed -e "s#+00:00##"'
          JOB_TIMESTAMP = JOB_TIMESTAMP.trim()

          if (params.Host_CN_CI_2nd_Server_Flag != null) {
            new_host_flag = params.Host_CN_CI_2nd_Server_Flag
            if (new_host_flag) {
              new_host = params.Host_CN_CI_2nd_Server
              new_host_user = params.Host_CN_CI_2nd_Server_Login
              echo "1st Node   is ${NODE_NAME}"
              echo "2nd Node   is ${new_host}"
            } else {
              echo "Node       is ${NODE_NAME}"
            }
          } else {
            echo "Node       is ${NODE_NAME}"
          }
          echo "Git URL    is ${GIT_URL}"

          removeGitHubInfo()
          if (env.ghprbPullId != null) {
            echo "======= THIS IS A PULL REQUEST ======"
            echo "PR ID      is ${env.ghprbPullId}"
            echo "PR LINK    is ${env.ghprbPullLink}"
            echo "PR TITLE   is ${env.ghprbPullTitle}"
            sh "./ci-scripts/doGitHubPullRequestTempMerge.sh --src-branch ${env.ghprbSourceBranch} --src-commit ${env.ghprbActualCommit} --target-branch ${env.ghprbTargetBranch} --target-commit ${GIT_COMMIT}"
            sh "sleep 10"
            mme_tag = 'ci-temp'
            mme_branch = env.ghprbSourceBranch
          } else {
            echo "======= THIS IS A PUSH EVENT ======"
            echo "Git Branch is ${GIT_BRANCH}"
            echo "Git Commit is ${GIT_COMMIT}"
            // Making a hard copy of the SHA-ONE
            getCommitSha()
          }
        }
      }
    }
    stage ('Prepare Source Code') {
      steps {
        script {
          sh "git clean -x -d -f > /dev/null 2>&1"
          sh "tar -cjhf /tmp/openair-mme.tar.bz2 ."
          sh "mv /tmp/openair-mme.tar.bz2 ."
          copyTo2ndServer('openair-mme.tar.bz2', new_host_flag, new_host_user, new_host)
          sh "mkdir -p archives"
          if (new_host_flag) {
            sh "mkdir -p archives/oai-mme-cfg"
          }
        }
      }
    }
    stage('Build Core Network Function') {
      parallel {
        stage ('Build MME Image') {
          steps {
            script {
              if (env.ghprbPullId != null) {
                // Building a temporary image
                myShCmd('docker image prune --force', new_host_flag, new_host_user, new_host)
                myShCmd('docker build --target oai-mme --tag oai-mme:ci-temp --file ci-scripts/Dockerfile.ubuntu18.04 --build-arg EURECOM_PROXY="http://proxy.eurecom.fr:8080" --build-arg BUILD_FOR_CI="True" --build-arg CI_SRC_BRANCH="' + env.ghprbSourceBranch + '" --build-arg CI_SRC_COMMIT="' + env.ghprbActualCommit + '" --build-arg CI_DEST_BRANCH="develop" . > archives/mme_docker_image_build.log 2>&1', new_host_flag, new_host_user, new_host)
              } else {
                // Currently this pipeline only runs for pushes to `develop` branch
                // First clean image registry
                myShCmd('docker image rm oai-mme:develop', new_host_flag, new_host_user, new_host)
                myShCmd('docker image prune --force', new_host_flag, new_host_user, new_host)
                myShCmd('docker build --target oai-mme --tag oai-mme:develop --file ci-scripts/Dockerfile.ubuntu18.04 --build-arg EURECOM_PROXY="http://proxy.eurecom.fr:8080" --build-arg CI_SRC_BRANCH="develop" . > archives/mme_docker_image_build.log 2>&1', new_host_flag, new_host_user, new_host)
              }
              myShCmd('docker image ls >> archives/mme_docker_image_build.log', new_host_flag, new_host_user, new_host)
            }
          }
          post {
            always {
              script {
                copyFrom2ndServer('archives/mme_docker_image_build.log', 'archives', new_host_flag, new_host_user, new_host)
              }
            }
            success {
              sh "echo 'OAI-MME DOCKER IMAGE BUILD: OK' >> archives/mme_docker_image_build.log"
            }
            unsuccessful {
              sh "echo 'OAI-MME DOCKER IMAGE BUILD: KO' >> archives/mme_docker_image_build.log"
            }
          }
        }
        // Running CPPCHECK in parallel to gain time
        stage ('Static Code Analysis') {
          steps {
            script {
              // Running on xenial to have 1.72 version of cppcheck
              myShCmd('docker run --name ci-cn-cppcheck -d ubuntu:xenial /bin/bash -c "sleep infinity"', new_host_flag, new_host_user, new_host)
              myShCmd('docker exec -it ci-cn-cppcheck /bin/bash -c "apt-get update && apt-get upgrade --yes" > archives/cppcheck_install.log', new_host_flag, new_host_user, new_host)
              myShCmd('docker exec -it ci-cn-cppcheck /bin/bash -c "apt-get install --yes cppcheck bzip2" >> archives/cppcheck_install.log', new_host_flag, new_host_user, new_host)

              myShCmd('docker cp ./openair-mme.tar.bz2 ci-cn-cppcheck:/home', new_host_flag, new_host_user, new_host)
              myShCmd('docker exec -it ci-cn-cppcheck /bin/bash -c "cd /home && tar -xjf openair-mme.tar.bz2"', new_host_flag, new_host_user, new_host)
              myShCmd('docker exec -it ci-cn-cppcheck /bin/bash -c "rm -f /home/openair-mme.tar.bz2"', new_host_flag, new_host_user, new_host)

              myShCmd('docker exec -it ci-cn-cppcheck /bin/bash -c "cd /home && cppcheck --enable=warning --force --xml --xml-version=2 -i src/oai_sgw -i src/sgw -i src/fluid/fluidmsg/test -i src/gtpv2-c/nwgtpv2c-0.11/test-app -i src/nas/test -i src/test -i src/oai_hss/tests -i src/utils/bstr/bstest.c -i src/utils/bstr/test.cpp -i src/utils/bstr/testaux.c --suppressions-list=ci-scripts/cppcheck_suppressions.list -I src/common -I src/common/itti -I src/common/itti_analyzer/common -I src/common/itti_analyzer/libbuffers -I src/common/itti_analyzer/libparser -I src/common/itti_analyzer/libresolver -I src/mme -I src/mme_app -I src/nas -I src/nas/api/mme -I src/nas/api/network -I src/nas/emm -I src/nas/emm/msg -I src/nas/emm/sap -I src/nas/esm -I src/nas/esm/msg -I src/nas/esm/sap -I src/nas/ies -I src/nas/util -I src/oai_mme -I src/s10 -I src/s11 -I src/s1ap -I src/s6a -I src/sctp -I src/secu -I src/udp -I src/utils -I src/utils/hashtable src 2> cppcheck.xml 1> cppcheck_build.log"', new_host_flag, new_host_user, new_host)
            }
          }
          post {
            always {
              script {
                myShCmd('docker cp ci-cn-cppcheck:/home/cppcheck.xml archives', new_host_flag, new_host_user, new_host)
                myShCmd('docker cp ci-cn-cppcheck:/home/cppcheck_build.log archives', new_host_flag, new_host_user, new_host)
                copyFrom2ndServer('archives/cppcheck*.*', 'archives', new_host_flag, new_host_user, new_host)
                // no need to keep the cppcheck container
                myShCmd('docker rm -f ci-cn-cppcheck', new_host_flag, new_host_user, new_host)
              }
            }
            success {
              sh "echo 'CPPCHECK: OK' >> archives/cppcheck_install.log"
            }
            unsuccessful {
              sh "echo 'CPPCHECK: KO' >> archives/cppcheck_install.log"
            }
          }
        }
        // Running CLANG-FORMATTING check in parallel to gain time
        stage ('Code Formatting Checker') {
          steps {
            script {
              myShCmd('docker run --name ci-cn-clang-formatter -d ubuntu:bionic /bin/bash -c "sleep infinity"', new_host_flag, new_host_user, new_host)
              myShCmd('docker exec -it ci-cn-clang-formatter /bin/bash -c "apt-get update && apt-get upgrade --yes" > archives/clang_format_install.log', new_host_flag, new_host_user, new_host)
              myShCmd('docker exec -it ci-cn-clang-formatter /bin/bash -c "apt-get install --yes git tree bzip2" >> archives/clang_format_install.log', new_host_flag, new_host_user, new_host)

              myShCmd('docker cp ./openair-mme.tar.bz2 ci-cn-clang-formatter:/home', new_host_flag, new_host_user, new_host)
              myShCmd('docker exec -it ci-cn-clang-formatter /bin/bash -c "cd /home && tar -xjf openair-mme.tar.bz2"', new_host_flag, new_host_user, new_host)
              myShCmd('docker exec -it ci-cn-clang-formatter /bin/bash -c "rm -f /home/openair-mme.tar.bz2"', new_host_flag, new_host_user, new_host)

              // We install a dedicated version (installed on our CI server).
              myShCmd('docker cp /opt/clang-format/9.0.0/bin/clang-format ci-cn-clang-formatter:/usr/local/bin', new_host_flag, new_host_user, new_host)
              if (env.ghprbPullId != null) {
                myShCmd('docker exec -it ci-cn-clang-formatter /bin/bash -c "cd /home && ./ci-scripts/checkCodingFormattingRules.sh --src-branch ' + env.ghprbSourceBranch +' --target-branch ' + env.ghprbTargetBranch + '"', new_host_flag, new_host_user, new_host)
              } else {
                myShCmd('docker exec -it ci-cn-clang-formatter /bin/bash -c "cd /home && ./ci-scripts/checkCodingFormattingRules.sh"', new_host_flag, new_host_user, new_host)
              }
            }
          }
          post {
            always {
              script {
                myShCmd('docker cp ci-cn-clang-formatter:/home/src/oai_rules_result.txt src', new_host_flag, new_host_user, new_host)
                // May not have been generated
                try {
                  myShCmd('docker cp ci-cn-clang-formatter:/home/src/oai_rules_result_list.txt src', new_host_flag, new_host_user, new_host)
                } catch (Exception e) {
                  echo "Failed to copy src/oai_rules_result_list.txt! It may not have been generated. That's OK!"
                }
                copyFrom2ndServer('archives/clang_format*.*', 'archives', new_host_flag, new_host_user, new_host)
                copyFrom2ndServer('src/oai_rules*.*', 'src', new_host_flag, new_host_user, new_host)
                // no need to keep the clang-formatter container
                myShCmd('docker rm -f ci-cn-clang-formatter', new_host_flag, new_host_user, new_host)
              }
            }
          }
        }
      }
    }
    stage('Deploy Sanity Check Test') {
      stages {
        stage('Create Docker Networks') {
          steps {
            script {
              myShCmd('python3 ./ci-scripts/sanityCheckDeploy.py --action=CreateNetworks', new_host_flag, new_host_user, new_host)
            }
          }
        }
        stage('Deploy Cassandra') {
          steps {
            script {
              myShCmd('python3 ./ci-scripts/sanityCheckDeploy.py --action=DeployCassandra', new_host_flag, new_host_user, new_host)
            }
          }
          post {
            always {
              script {
                copyFrom2ndServer('archives/cassandra_status.log', 'archives', new_host_flag, new_host_user, new_host)
              }
            }
            success {
              sh "echo 'CASSANDRA START: OK' >> archives/cassandra_status.log"
            }
            unsuccessful {
              sh "echo 'CASSANDRA START: KO' >> archives/cassandra_status.log"
            }
          }
        }
        stage('Deploy OAI-HSS') {
          steps {
            script {
              myShCmd('python3 ./ci-scripts/sanityCheckDeploy.py --action=DeployHSS --tag=develop', new_host_flag, new_host_user, new_host)
            }
          }
          post {
            always {
              script {
                try {
                  copyFrom2ndServer('archives/hss_config.log', 'archives', new_host_flag, new_host_user, new_host)
                } catch (Exception e) {
                  echo "Failed to copy archives/hss_config.log"
                }
              }
            }
            success {
              sh "echo 'OAI-HSS CONFIG: OK' >> archives/hss_config.log"
            }
            unsuccessful {
              sh "echo 'OAI-HSS CONFIG: KO' >> archives/hss_config.log"
            }
          }
        }
        stage('Deploy OAI-MME') {
          steps {
            script {
              myShCmd('python3 ./ci-scripts/sanityCheckDeploy.py --action=DeployMME --tag=' + mme_tag, new_host_flag, new_host_user, new_host)
            }
          }
          post {
            always {
              script {
                myShCmd('docker cp ci-oai-mme:/openair-mme/etc/. archives/oai-mme-cfg', new_host_flag, new_host_user, new_host)
                copyFrom2ndServer('archives/mme_config.log', 'archives', new_host_flag, new_host_user, new_host)
                copyFrom2ndServer('archives/oai-mme-cfg/*.*', 'archives/oai-mme-cfg', new_host_flag, new_host_user, new_host)
              }
            }
            success {
              sh "echo 'OAI-MME CONFIG: OK' >> archives/mme_config.log"
            }
            unsuccessful {
              sh "echo 'OAI-MME CONFIG: KO' >> archives/mme_config.log"
            }
          }
        }
      }
    }
    stage ('Start-Check-Stop OAI cNFs') {
      steps {
        script {
          myShCmd('python3 ./ci-scripts/sanityCheckDeploy.py --action=StartHSS --tag=develop', new_host_flag, new_host_user, new_host)
          sh "sleep 2"
          myShCmd('python3 ./ci-scripts/sanityCheckDeploy.py --action=StartMME --tag=' + mme_tag, new_host_flag, new_host_user, new_host)
          sh "sleep 40"
          myShCmd('python3 ./ci-scripts/sanityCheckDeploy.py --action=StopHSS --tag=develop', new_host_flag, new_host_user, new_host)
          myShCmd('python3 ./ci-scripts/sanityCheckDeploy.py --action=StopMME --tag=' + mme_tag, new_host_flag, new_host_user, new_host)
          sh "sleep 2"
          myShCmd('python3 ./ci-scripts/sanityCheckDeploy.py --action=RetrieveLogsHSS --tag=develop', new_host_flag, new_host_user, new_host)
          myShCmd('python3 ./ci-scripts/sanityCheckDeploy.py --action=RetrieveLogsMME --tag=' + mme_tag, new_host_flag, new_host_user, new_host)
          copyFrom2ndServer('archives/*_check_run.log', 'archives', new_host_flag, new_host_user, new_host)
          sh "python3 ./ci-scripts/verifySanityCheckDeployment.py --job_name=${JOB_NAME} --job_id=${BUILD_ID}"
        }
      }
      post {
        success {
          sh "echo 'OAI-HSS CHECK START/STOP: OK' > archives/hss_cnf_check_start.log"
          sh "echo 'OAI-MME CHECK START/STOP: OK' > archives/mme_cnf_check_start.log"
        }
        unsuccessful {
          // If anything wrong occurs, we still try to copy
          myShCmd('python3 ./ci-scripts/sanityCheckDeploy.py --action=RetrieveLogsHSS --tag=develop', new_host_flag, new_host_user, new_host)
          myShCmd('python3 ./ci-scripts/sanityCheckDeploy.py --action=RetrieveLogsMME --tag=' + mme_tag, new_host_flag, new_host_user, new_host)
          copyFrom2ndServer('archives/*_check_run.log', 'archives', new_host_flag, new_host_user, new_host)
          sh "echo 'OAI-HSS CHECK START/STOP: KO' > archives/hss_cnf_check_start.log"
          sh "echo 'OAI-MME CHECK START/STOP: KO' > archives/mme_cnf_check_start.log"
        }
      }
    }
    stage ('Undeploy Sanity Check Test') {
      steps {
        script {
          // Killing all containers
          myShCmd('python3 ./ci-scripts/sanityCheckDeploy.py --action=RemoveAllContainers', new_host_flag, new_host_user, new_host)
          // Removing all intermediate networks
          myShCmd('python3 ./ci-scripts/sanityCheckDeploy.py --action=RemoveNetworks', new_host_flag, new_host_user, new_host)
        }
      }
    }
    stage ('Testing in FED environment') {
      steps {
        script {
          localStatus = build job: 'CI-OpenAir-EPC-FED',
            parameters: [
              string(name: 'MME_TAG', value: String.valueOf(mme_tag)),
              string(name: 'MME_BRANCH', value: String.valueOf(mme_branch))
            ], propagate: false
          localResult = localStatus.getResult()

          if (localStatus.resultIsBetterOrEqualTo('SUCCESS')) {
            echo "Federation Test Job is OK"
          } else {
            echo "Federation Test Job is KO"
            sh "ci-scripts/fail.sh"
          }
        }
      }
      post {
        always {
          script {
            copyArtifacts(projectName: 'CI-OpenAir-EPC-FED',
                          filter: 'test_results_oai_epc.html',
                          selector: lastCompleted())
          }
        }
      }
    }
  }
  post {
    success {
      script {
        def message = "Build job #" + BUILD_ID + " completed"
        updateGithubCommitStatus(currentBuild, message)
        def socialMessage = "OAI " + JOB_NAME + " build (" + BUILD_ID + "): passed (" + BUILD_URL + ")"
        sendSocialMediaMessage('ci-epc', 'good', socialMessage)
      }
    }
    failure {
      script {
        def message = "Build job #" + BUILD_ID + " : One step of job failed"
        updateGithubCommitStatus(currentBuild, message)
        def socialMessage = "OAI " + JOB_NAME + " build (" + BUILD_ID + "): failed (" + BUILD_URL + ")"
        sendSocialMediaMessage('ci-epc', 'danger', socialMessage)
      }
    }
    unstable {
      script {
        def message = "Build job #" + BUILD_ID + " : One step of job is unstable"
        updateGithubCommitStatus(currentBuild, message)
        def socialMessage = "OAI " + JOB_NAME + " build (" + BUILD_ID + "): unstable (" + BUILD_URL + ")"
        sendSocialMediaMessage('ci-epc', 'danger', socialMessage)
      }
    }
    aborted {
      script {
        def message = "Build job #" + BUILD_ID + " aborted: pipeline script issue?"
        updateGithubCommitStatus(currentBuild, message)
        def socialMessage = "OAI " + JOB_NAME + " build (" + BUILD_ID + "): aborted (" + BUILD_URL + ")"
        sendSocialMediaMessage('ci-epc', 'danger', socialMessage)
      }
    }
    cleanup {
      script {
        // Killing all containers
        myShCmd('python3 ./ci-scripts/sanityCheckDeploy.py --action=RemoveAllContainers', new_host_flag, new_host_user, new_host)
        // Removing the networks
        myShCmd('python3 ./ci-scripts/sanityCheckDeploy.py --action=RemoveNetworks', new_host_flag, new_host_user, new_host)
        // In case of build failure, we might have temporary containers still running. TBD!

        // Removing temporary / intermediate images
        try {
          if (env.ghprbPullId != null) {
            myShCmd('docker image rm --force oai-mme:ci-temp', new_host_flag, new_host_user, new_host)
          }
        } catch (Exception e) {
          echo "We failed to delete the OAI-MME temp image"
        }
        try {
          myShCmd('docker image prune --force', new_host_flag, new_host_user, new_host)
        } catch (Exception e) {
          echo "We failed to prune all unneeded intermediate images"
        }

        // Zipping all archived log files
        sh "zip -r -qq docker_logs.zip archives"
        if (fileExists('docker_logs.zip')) {
          archiveArtifacts artifacts: 'docker_logs.zip'
        }
        // Generating the HTML report
        if (env.ghprbPullId != null) {
          sh "python3 ci-scripts/generateHtmlReport.py --job_name=${JOB_NAME} --job_id=${BUILD_ID} --job_url=${BUILD_URL} --git_url=${GIT_URL} --git_src_branch=${env.ghprbSourceBranch} --git_src_commit=${env.ghprbActualCommit} --git_pull_request=True --git_target_branch=${env.ghprbTargetBranch} --git_target_commit=${GIT_COMMIT}"
          if (fileExists('test_results_oai_mme.html')) {
            sh "sed -i -e 's#TEMPLATE_PULL_REQUEST_LINK#${env.ghprbPullLink}#g' test_results_oai_mme.html"
            sh "sed -i -e 's#TEMPLATE_PULL_REQUEST_TEMPLATE#${env.ghprbPullTitle}#' test_results_oai_mme.html"
          }
          if (fileExists('test_results_oai_epc.html')) {
            sh "sed -i -e 's#TEMPLATE_PULL_REQUEST_LINK#${env.ghprbPullLink}#g' test_results_oai_epc.html"
            sh "sed -i -e 's#TEMPLATE_PULL_REQUEST_TEMPLATE#${env.ghprbPullTitle}#' test_results_oai_epc.html"
          }
        } else {
          sh "python3 ci-scripts/generateHtmlReport.py --job_name=${JOB_NAME} --job_id=${BUILD_ID} --job_url=${BUILD_URL} --git_url=${GIT_URL} --git_src_branch=${GIT_BRANCH} --git_src_commit=${GIT_COMMIT}"
        }
        if (fileExists('test_results_oai_mme.html')) {
          sh "sed -i -e 's#TEMPLATE_TIME#${JOB_TIMESTAMP}#' test_results_oai_mme.html"
          archiveArtifacts artifacts: 'test_results_oai_mme.html'
        }
        if (fileExists('test_results_oai_epc.html')) {
          sh "sed -i -e 's#TEMPLATE_TIME#${JOB_TIMESTAMP}#' test_results_oai_epc.html"
          archiveArtifacts artifacts: 'test_results_oai_epc.html'
        }
        // Sending an email to the last committer. Maybe not the Pull Request's author.
        def emailTo = getCommitterEmail()
        emailext attachmentsPattern: '*results*.html',
          body: '''Hi,
Here are attached HTML report files for $PROJECT_NAME - Build # $BUILD_NUMBER - $BUILD_STATUS!

Regards,
OAI CI Team''',
          replyTo: 'no-reply@openairinterface.org',
          subject: '$PROJECT_NAME - Build # $BUILD_NUMBER - $BUILD_STATUS!',
          to: emailTo
      }
    }
  }
}

// Removing all info -- do not know if git clean command removes them
def removeGitHubInfo() {
  if (fileExists('.git/remote-url')) {
    sh "rm -f .git/remote-url"
  }
  if (fileExists('.git/current-commit')) {
    sh "rm -f .git/current-commit"
  }
  if (fileExists('.git/commit-email')) {
    sh "rm -f .git/commit-email"
  }
}

// GitHub retrieve email of last committer
def getCommitterEmail() {
  if (!fileExists('.git/commit-email')) {
    sh "git log -1 --pretty=format:\"%ce\" > .git/commit-email"
    // Workaround for issue when merge to develop from the Pull Request GitHub webpage
    // Click on merge button creates a commit with an email address in noreply@github.com
    sh "if [ `egrep -c \"noreply@github.com\" .git/commit-email` -eq 1 ]; then echo \"raphael.defosseux@openairinterface.org\" > .git/commit-email; fi"
  }
  return readFile(".git/commit-email").trim()
}

// Github commit update functions
def getRepoURL() {
  if (!fileExists('.git/remote-url')) {
    sh "git config --get remote.origin.url > .git/remote-url"
  }
  return readFile(".git/remote-url").trim()
}

def getCommitSha() {
  if (!fileExists('.git/current-commit')) {
    sh "git rev-parse HEAD > .git/current-commit"
  }
  return readFile(".git/current-commit").trim()
}

def updateGithubCommitStatus(build, jobMessage) {
  // workaround https://issues.jenkins-ci.org/browse/JENKINS-38674
  repoUrl = getRepoURL()
  commitSha = getCommitSha()

  step([
    $class: 'GitHubCommitStatusSetter',
    reposSource: [$class: "ManuallyEnteredRepositorySource", url: repoUrl],
    commitShaSource: [$class: "ManuallyEnteredShaSource", sha: commitSha],
    errorHandlers: [[$class: 'ShallowAnyErrorHandler']],
    statusResultSource: [
      $class: 'ConditionalStatusResultSource',
      results: [
        [$class: 'AnyBuildResult', state: build.currentResult, message: jobMessage]
      ]
    ]
  ])
}

def copyTo2ndServer(filename, flag, user, host) {
  if (flag) {
    if ("openair-mme.tar.bz2".equals(filename)) {
      sh "ssh ${user}@${host} 'rm -rf /tmp/CI-CN-MME'"
      sh "ssh ${user}@${host} 'mkdir -p /tmp/CI-CN-MME'"
    }
    sh "scp ${filename} ${user}@${host}:/tmp/CI-CN-MME"
    if ("openair-mme.tar.bz2".equals(filename)) {
      sh "ssh ${user}@${host} 'cd /tmp/CI-CN-MME && tar -xjf ${filename}'"
      sh "ssh ${user}@${host} 'mkdir -p /tmp/CI-CN-MME/archives'"
      sh "ssh ${user}@${host} 'mkdir -p /tmp/CI-CN-MME/archives/oai-hss-cfg'"
      sh "ssh ${user}@${host} 'mkdir -p /tmp/CI-CN-MME/archives/oai-mme-cfg'"
    }
  }
}

def copyFrom2ndServer(filename, target, flag, user, host) {
  if (flag) {
    sh "scp ${user}@${host}:/tmp/CI-CN-MME/${filename} ${target}"
  }
}

def myShCmd(cmd, flag, user, host) {
  if (flag) {
    sh "ssh -t -t ${user}@${host} 'cd /tmp/CI-CN-MME && ${cmd}'"
  } else {
    sh "${cmd}"
  }
}

def myShRetCmd(cmd, flag, user, host) {
  if (flag) {
    ret = sh returnStdout: true, script: "ssh -t -t ${user}@${host} 'cd /tmp/CI-CN-MME && ${cmd}'"
  } else {
    ret = sh returnStdout: true, script: "${cmd}"
  }
  ret = ret.trim()
  return ret
}
